package com.lsf.wechat.service.impl;

import com.lsf.wechat.message.Article;
import com.lsf.wechat.message.LinkMessage;
import com.lsf.wechat.message.NewsMessage;
import com.lsf.wechat.message.TextMessage;
import com.lsf.wechat.service.MessageService;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkTpwdCreateResponse;
import com.lsf.wechat.message.*;
import com.lsf.wechat.utils.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
/*import com.taobao.api.request.ItemSellerGetRequest;
import com.taobao.api.response.ItemSellerGetResponse;
import com.taobao.api.request.WirelessShareTpwdQueryRequest;
import com.taobao.api.response.WirelessShareTpwdQueryResponse;*/


/**
 * @author lsf
 * @create 2018-07-11 15:33
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageServiceImpl.class);
    @Override
    public String newMessageRequest(HttpServletRequest request) {
        String respMessage = null;
        //String serverUrl = "http://gw.api.tbsandbox.com/router/rest"; //沙箱环境应用
        String serverUrl = "http://gw.api.taobao.com/router/rest"; //TOP服务地址，正式环境
        String appKey = "28127620"; // 可替换为您的沙箱环境应用的AppKey
        String appSecret = "75300fcdabea5f1689b04674d009ed08"; // 可替换为您的沙箱环境应用的AppSecret
        String sessionKey = "70000100e079719266f1bd73c408ecf5e477a0e7371006860aefba9d4f86a9bae91f4622673904154"; // 必须替换为沙箱账号授权得到的真实有效SessionKey

        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.xmlToMap(request);
            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 消息内容
            String content = requestMap.get("Content");
            LOGGER.info("FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType);

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
                //这里根据关键字执行相应的逻辑
                /*if(content.equals("xxx")){
                }*/
                //淘口令生成
                TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
                TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
                req.setUserId("123");
                req.setText("长度大于5个字符");
                req.setUrl("https://uland.taobao.com/");
                req.setLogo("https://uland.taobao.com/");
                req.setExt("{}");
                TbkTpwdCreateResponse rsp = client.execute(req);
                System.out.println(rsp.getBody());

               /* TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
                WirelessShareTpwdQueryRequest req = new WirelessShareTpwdQueryRequest();
                req.setPasswordContent(content);
                WirelessShareTpwdQueryResponse response = client.execute(req);
*/

                TextMessage text = new TextMessage();
                text.setContent("https://uland.taobao.com/的淘口令:"+ rsp.getBody());
                text.setToUserName(fromUserName);
                text.setFromUserName(toUserName);
                text.setCreateTime(new Date().getTime());
                text.setMsgType(msgType);
                text.setFuncFlag(0);
                respMessage = MessageUtil.textMessageToXml(text);
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                String eventType = requestMap.get("Event");// 事件类型
                // 订阅
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {

                    //对图文消息
                    NewsMessage newmsg=new NewsMessage();
                    newmsg.setToUserName(fromUserName);
                    newmsg.setFromUserName(toUserName);
                    newmsg.setCreateTime(new Date().getTime());
                    newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
                    newmsg.setFuncFlag(0);
                    List<Article> articleList = new ArrayList<>();

                    Article article = new Article();
                    article.setTitle("我是一个图文");
                    article.setDescription("我是描述信息");
                    article.setPicUrl("https://sfault-avatar.b0.upaiyun.com/110/007/1100070317-5abcb09d42224_huge256");
                    article.setUrl("https://segmentfault.com/u/panzi_5abcaf30a5e6b");

                    articleList.add(article);
                    // 设置图文消息个数
                    newmsg.setArticleCount(articleList.size());
                    // 设置图文消息包含的图文集合
                    newmsg.setArticles(articleList);
                    // 将图文消息对象转换成xml字符串
                    respMessage = MessageUtil.newsMessageToXml(newmsg);

                }
                // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅

                }
                // 自定义菜单点击事件
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    String eventKey = requestMap.get("EventKey");// 事件KEY值，与创建自定义菜单时指定的KEY值对应
                    if (eventKey.equals("return_content")) {

                       /* TextMessage text = new TextMessage();
                        text.setContent("赞赞赞");
                        text.setToUserName(fromUserName);
                        text.setFromUserName(toUserName);
                        text.setCreateTime(new Date().getTime());
                        text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                        respMessage = MessageUtil.textMessageToXml(text);*/
                    }
                }
            }
            //链接消息
            else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)){
                LOGGER.info("链接消息:");

                LinkMessage link = new LinkMessage();
                link.setContent("正在帮您查询...");
                //link.setImage("http://htmltest.lishengfeng.cn/clothes.jpg");
                //link.setMsgId(Long.valueOf(msgId));
                link.setCreateTime(new Date().getTime());
                link.setMsgType(msgType);
                link.setToUserName(fromUserName);
                link.setFromUserName(toUserName);
                link.setTitle("我是一个链接/淘口令"+content);
                link.setKouling("返回的淘口令");
                link.setLowPrice("原价："+"11.11");
                link.setCoupon("优惠券："+"5.11");
                link.setRebate("返利："+"1.11");
                respMessage = MessageUtil.linkMessageToXml(link);
            }

            //发送图片消息
            else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){
                LOGGER.info("图片消息:");
                /*ImageMessage imageMessage = new ImageMessage();
                imageMessage.setToUserName(fromUserName);
                imageMessage.setFromUserName(toUserName);
                imageMessage.setCreateTime(new Date().getTime());
                imageMessage.setMsgType(msgType);
                imageMessage.setMediaId("http://www.xianyun123.cn:8080/upload/upload/F0315C88032448EB8E0DC71E9BCFD2D6/1568012347000.jpg");
                imageMessage.setPicUrl("http://www.xianyun123.cn:8080/upload/upload/F0315C88032448EB8E0DC71E9BCFD2D6/1568012347000.jpg");
                imageMessage.setMsgId(123);
                respMessage = MessageUtil.imageMessageToXml(imageMessage);*/

                TextMessage text = new TextMessage();
                text.setContent("您发了一个图片:");
                text.setToUserName(fromUserName);
                text.setFromUserName(toUserName);
                text.setCreateTime(new Date().getTime());
                text.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
                text.setFuncFlag(0);
                //text.setMsgId(12222);
                respMessage = MessageUtil.textMessageToXml(text);
            }

        }
        catch (Exception e) {
            LOGGER.error("error......");
        }
        return respMessage;
    }
}
